package com.gitee.easyopen.verify;

import java.security.interfaces.RSAPrivateKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.gitee.easyopen.ApiContext;
import com.gitee.easyopen.ApiParam;
import com.gitee.easyopen.exception.ApiException;
import com.gitee.easyopen.util.MD5Util;
import com.gitee.easyopen.util.RSAUtil;

public class DefaultRsaVerifier implements Verifier {

    @Override
    public boolean verify(ApiParam apiParam, String secret) {
        boolean same = false;
        try {
            String privateKeyStr = ApiContext.getApiConfig().getPrivateKey();
            // 私钥
            RSAPrivateKey privateKey = RSAUtil.getPrivateKey(privateKeyStr);
            // 密文
            String sign = apiParam.fatchSignAndRemove();
            // 私钥解密密文，得到明文
            String decodedContent = RSAUtil.privateDecrypt(sign, privateKey);
            
            // 明文
            String content = this.buildContent(apiParam);
            
            // 明文跟解出来的是否一样
            same = MD5Util.encrypt(content).equals(MD5Util.encrypt(decodedContent));
            
        } catch (Exception e) {
            throw new ApiException(e);
        }
        
        return same;
    }

    // 原文
    public String buildContent(Map<String, ?> paramsMap) {
        Set<String> keySet = paramsMap.keySet();
        List<String> paramNames = new ArrayList<String>(keySet);

        Collections.sort(paramNames);

        StringBuilder paramNameValue = new StringBuilder();

        for (String paramName : paramNames) {
            paramNameValue.append(paramName).append(paramsMap.get(paramName));
        }

        return paramNameValue.toString();
    }

}
